package com.basic.library.view.recyclerview;

import static com.chad.library.adapter.base.BaseQuickAdapter.EMPTY_VIEW;
import static com.chad.library.adapter.base.BaseQuickAdapter.FOOTER_VIEW;
import static com.chad.library.adapter.base.BaseQuickAdapter.HEADER_VIEW;
import static com.chad.library.adapter.base.BaseQuickAdapter.LOADING_VIEW;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.basic.library.R;
import com.basic.library.brvah.MyBaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;


/**
 * 分隔线装饰
 * 多布局每个item需要相同的间隔时，itemType必须是0或者<-1000
 * r若是复杂的多布局，那就不要设置分割线，item内部实现上下边距
 */
public class RecycleViewDivider extends RecyclerView.ItemDecoration {
    public static final int VERTICAL = 0;//竖线
    public static final int HORIZONTAL = 1;//横线
    public static final int GRID = 2;//网格
    private Paint mPaint;
    private Drawable mDivider;
    private int mDividerHeight = 2;//分割线高度，默认为1px
    private int mOrientation;//列表的方向：LinearLayoutManager.VERTICAL或LinearLayoutManager.HORIZONTAL
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private boolean endLineSpace = false; //当item一个个添加的时候，不要设置为true
    private boolean topLine = false;
    private int leftPadding;
    private int rightPadding;
    boolean includeEdge = false;

    /**
     * 默认分割线：高度为2px，颜色为灰色
     *
     * @param context
     * @param orientation 列表方向
     */
    public RecycleViewDivider(Context context, int orientation) {
        mDividerHeight = context.getResources().getDimensionPixelOffset(R.dimen.divider);
        if (orientation != VERTICAL && orientation != HORIZONTAL
                && orientation != GRID) {
            throw new IllegalArgumentException("请输入正确的参数！");
        }
        mOrientation = orientation;

//        final TypedArray a = context.obtainStyledAttributes(ATTRS);
//        mDivider = a.getDrawable(0);
//        a.recycle();
    }

    public int getLeftPadding() {
        return leftPadding;
    }

    public RecycleViewDivider setLeftPadding(int leftPadding) {
        this.leftPadding = leftPadding;
        return this;
    }

    public int getRightPadding() {
        return rightPadding;
    }

    public RecycleViewDivider setRightPadding(int rightPadding) {
        this.rightPadding = rightPadding;
        return this;
    }

    public RecycleViewDivider(Context context, int orientation, boolean endLine) {
        this(context, orientation);
        this.endLineSpace = endLine;
    }

    public RecycleViewDivider setEndLineSpace(boolean endLineSpace) {
        this.endLineSpace = endLineSpace;
        return this;
    }

    public RecycleViewDivider setTopLine(boolean topLine) {
        this.topLine = topLine;
        return this;
    }

    public RecycleViewDivider setIncludeEdge(boolean includeEdge) {
        this.includeEdge = includeEdge;
        return this;
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation 列表方向
     * @param drawableId  分割线图片
     */
    public RecycleViewDivider(Context context, int orientation, int drawableId) {
        this(context, orientation);
        mDivider = ContextCompat.getDrawable(context, drawableId);
        mDividerHeight = mDivider.getIntrinsicHeight();
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation   列表方向
     * @param dividerHeight 分割线高度 dp
     * @param dividerColor  分割线颜色
     */
    public RecycleViewDivider(Context context, int orientation, float dividerHeight, int dividerColor) {
        this(context, orientation);
        mDividerHeight = dip2px(context, dividerHeight);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(dividerColor);
        mPaint.setStyle(Paint.Style.FILL);
    }


    //获取分割线尺寸,多布局itemType < -1000 时，每个item都有同样的间隔
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter != null)

            if (layoutManager instanceof GridLayoutManager) {
                GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
                boolean reverse = gridLayoutManager.getReverseLayout();
                int orientation = gridLayoutManager.getOrientation();
                int headerCount = 0;
                if (adapter instanceof BaseQuickAdapter) {
                    //加了N个header，parent.getChildLayoutPosition(view)的值好像还是只算了1个header
                    BaseQuickAdapter ad = (BaseQuickAdapter) adapter;
                    if (ad.getHeaderLayoutCount() != 0)
                        headerCount = 1;
                }
                int itemPosition = parent.getChildLayoutPosition(view) - headerCount;
                int spanCount = gridLayoutManager.getSpanCount();
                int type = gridLayoutManager.getItemViewType(view);
                if (type >= 0 && !isFixedViewType(type))
                    if (orientation == 1) { //竖直显示
                        int index = 0;
                        for (int i = itemPosition - 1; i >= 0; i--) {
                            if (adapter.getItemViewType(i) >= 0) {
                                index++;
                            } else {
                                break;
                            }
                        }
                        if (topLine) {
                            if (itemPosition < spanCount && itemPosition >= 0) {
                                if (reverse)
                                    outRect.bottom = mDividerHeight;
                                else
                                    outRect.top = mDividerHeight;
                            }
                        }
                        if (itemPosition >= 0) {
                            if (reverse)
                                outRect.top = mDividerHeight;
                            else
                                outRect.bottom = mDividerHeight;
                        }
                        if (headerCount == 1 && itemPosition == -1) {
                            outRect.left = 0;
                            outRect.right = 0;
                        } else {
//                            int column = itemPosition % spanCount;
                            int column = index % spanCount;
                            if (includeEdge) {
                                outRect.left = mDividerHeight - column * mDividerHeight / spanCount;
                                outRect.right = (column + 1) * mDividerHeight / spanCount;
                            } else {
                                outRect.left = column * mDividerHeight / spanCount;
                                outRect.right = mDividerHeight - (column + 1) * mDividerHeight / spanCount;
                            }
                        }
                    }
                if (orientation == 0) { //水平显示
                    int index = 0;
                    for (int i = itemPosition - 1; i >= 0; i--) {
                        if (adapter.getItemViewType(i) >= 0) {
                            index++;
                        } else {
                            break;
                        }
                    }
                    if (topLine) {
                        if (itemPosition < spanCount && itemPosition >= 0) {
                            if (reverse)
                                outRect.right = mDividerHeight;
                            else
                                outRect.left = mDividerHeight;
                        }
                    }
                    if (itemPosition >= 0) {
                        if (reverse)
                            outRect.left = mDividerHeight;
                        else
                            outRect.right = mDividerHeight;
                    }
                    if (headerCount == 1 && itemPosition == -1) {
                        outRect.top = 0;
                        outRect.bottom = 0;
                    } else {
                        int column = index % spanCount;
                        if (includeEdge) {
                            outRect.top = mDividerHeight - column * mDividerHeight / spanCount;
                            outRect.bottom = (column + 1) * mDividerHeight / spanCount;
                        } else {
                            outRect.top = column * mDividerHeight / spanCount;
                            outRect.bottom = mDividerHeight - (column + 1) * mDividerHeight / spanCount;
                        }
                    }
                }
            } else if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                boolean reverse = linearManager.getReverseLayout();
                int orientation = linearManager.getOrientation();
                boolean isMulti = adapter instanceof MyBaseMultiItemQuickAdapter;
                int headerCount = 0;
                if (adapter instanceof BaseQuickAdapter) {
                    //加了N个header，parent.getChildLayoutPosition(view)的值好像还是只算了1个header
                    BaseQuickAdapter ad = (BaseQuickAdapter) adapter;
                    if (ad.getHeaderLayoutCount() != 0)
                        headerCount = 1;
                }
                int itemPosition = parent.getChildLayoutPosition(view) - headerCount;
                boolean last = (itemPosition == adapter.getItemCount() - 1 - headerCount);
                if (itemPosition == 0) {
                    if (orientation == 1) { //竖直显示
                        if (!isMulti) {
                            //强制画第一个（item上边框top）
                            if (topLine) {
                                outRect.set(0, mDividerHeight, 0, mDividerHeight);
                            } else {
                                outRect.set(0, 0, 0, mDividerHeight);
                                if (reverse)
                                    outRect.set(0, mDividerHeight, 0, 0);
                                if (last && !endLineSpace)
                                    outRect.set(0, 0, 0, 0);
                            }
                        } else if (topLine) {
                            outRect.set(0, mDividerHeight, 0, 0);
                            if (reverse)
                                outRect.set(0, 0, 0, mDividerHeight);
                        } else
                            outRect.set(0, 0, 0, 0);
                    }
                    if (orientation == 0) { //水平显示
                        if (!isMulti) {
                            //强制画第一个（item上边框top）
                            if (topLine) {
                                outRect.set(mDividerHeight, 0, mDividerHeight, 0);
                            } else {
                                outRect.set(0, 0, mDividerHeight, 0);
                                if (reverse)
                                    outRect.set(mDividerHeight, 0, 0, 0);
                                if (last && !endLineSpace)
                                    outRect.set(0, 0, 0, 0);
                            }
                        } else if (topLine) {
                            outRect.set(mDividerHeight, 0, 0, 0);
                            if (reverse)
                                outRect.set(0, 0, mDividerHeight, 0);
                        } else
                            outRect.set(0, 0, 0, 0);
                    }
                } else if (itemPosition > 0 && (itemPosition <= adapter.getItemCount() - 1 - headerCount || endLineSpace)) {
                    //画的item下边框bottom
                    int type = linearManager.getItemViewType(view);
                    if (!isMulti)
                        setRect(outRect, last && !endLineSpace, reverse, orientation);
                    else {
                        if (type == 0 || type < -1000) {
                            outRect.set(0, mDividerHeight, 0, 0);
                            if (reverse)
                                outRect.set(0, 0, 0, mDividerHeight);
                        }
                        if (endLineSpace && itemPosition == adapter.getItemCount() - 1 - headerCount) { //最后一个，上下都画
                            outRect.set(0, mDividerHeight, 0, mDividerHeight);
                        }
                        if (orientation == 0) { //水平显示
                            if (type == 0 || type < -1000) {
                                outRect.set(mDividerHeight, 0, 0, 0);
                                if (reverse)
                                    outRect.set(0, 0, mDividerHeight, 0);
                            }
                            if (endLineSpace && itemPosition == adapter.getItemCount() - 1 - headerCount) { //最后一个，上下都画
                                outRect.set(mDividerHeight, 0, mDividerHeight, 0);
                            }
                        }
                    }
                }
            }
    }

    void setRect(Rect outRect, boolean lastNoEndLineSpace, boolean reverse, int orientation) {
        if (orientation == 0) { //水平显示
            outRect.set(0, 0, mDividerHeight, 0);
            if (reverse)
                outRect.set(mDividerHeight, 0, 0, 0);
            if (lastNoEndLineSpace)
                outRect.set(0, 0, 0, 0);
        } else {
            outRect.set(0, 0, 0, mDividerHeight);
            if (reverse)
                outRect.set(0, mDividerHeight, 0, 0);
            if (lastNoEndLineSpace)
                outRect.set(0, 0, 0, 0);
        }
    }

    //绘制分割线
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        if (mOrientation == VERTICAL) {
            drawVertical(c, parent);
        } else if (mOrientation == HORIZONTAL) {
            drawHorizontal(c, parent);
        } else if (mOrientation == GRID) {//网格
            drawGridLine(c, parent);
        }
    }

    //画横线
    private void drawHorizontal(Canvas canvas, RecyclerView parent) {
        final int left = parent.getPaddingLeft() + leftPadding;
        final int right = parent.getMeasuredWidth() - parent.getPaddingRight() - rightPadding;
        final int childSize = parent.getChildCount();
        int headerCount = 0;
        int start = 0;
        int end = 0;
        RecyclerView.Adapter adapter = parent.getAdapter();
        if (adapter instanceof BaseQuickAdapter) {
            //加了N个header，parent.getChildLayoutPosition(view)的值好像还是只算了1个header
            BaseQuickAdapter ad = (BaseQuickAdapter) adapter;
            if (ad.getHeaderLayoutCount() != 0)
                headerCount = 1;
        }
        if (headerCount == 1) {
            start = topLine ? 0 : 1;
        }
        end = endLineSpace ? 0 : 1;
        for (int i = start; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + layoutParams.bottomMargin;
            final int bottom = top + mDividerHeight;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            if (topLine && i == start) {
                if (mPaint != null) {
                    final int top1 = child.getTop() - layoutParams.topMargin;
                    final int bottom1 = top1 - mDividerHeight;
                    canvas.drawRect(left, top1, right, bottom1, mPaint);
                }
            }
            if (mPaint != null) {
                if (i < childSize - 1 || endLineSpace)
                    canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }

    //画竖线
    private void drawVertical(Canvas canvas, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize - 1; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + layoutParams.rightMargin;
            final int right = left + mDividerHeight;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            if (mPaint != null) {
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }

    private void drawGridLine(Canvas canvas, RecyclerView parent) {
        if (parent.getLayoutManager() instanceof GridLayoutManager) {
            final int top1 = parent.getPaddingTop();
            final int bottom1 = parent.getMeasuredHeight() - parent.getPaddingBottom();
            final int left1 = parent.getPaddingLeft();
            final int right1 = parent.getMeasuredWidth() - parent.getPaddingRight();

            int colums = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
            int countVertical = (int) Math.ceil(parent.getChildCount() / (double) colums) - 1;//横线的数量
            if (endLineSpace) {
                countVertical++;
            }
            //画横线
            for (int i = 0; i < countVertical; i++) {
                final View child = parent.getChildAt(i * colums);
                if (child != null) {
                    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                    final int top = child.getBottom() + layoutParams.bottomMargin;
                    final int bottom = top + mDividerHeight;
                    if (mDivider != null) {
                        mDivider.setBounds(left1, top, right1, bottom);
                        mDivider.draw(canvas);
                    }
                    if (mPaint != null) {
                        canvas.drawRect(left1, top, right1, bottom, mPaint);
                    }
                }
            }

            //画竖线
            for (int i = 0; i < colums - 1; i++) {
                Log.e("colums", i + "");
                final View child = parent.getChildAt(i);
                if (child != null) {
                    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                    final int left = child.getRight() + layoutParams.rightMargin;
                    final int right = left + mDividerHeight;
                    if (mDivider != null) {
                        mDivider.setBounds(left, top1, right, bottom1);
                        mDivider.draw(canvas);
                    }
                    if (mPaint != null) {
                        canvas.drawRect(left, top1, right, bottom1, mPaint);
                    }
                }
            }
        }
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @param context（DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    boolean isFixedViewType(int type) {
        return type == EMPTY_VIEW || type == HEADER_VIEW || type == FOOTER_VIEW || type ==
                LOADING_VIEW;
    }
}